package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpLogMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpLogMapper empLogMapper;

    @Override
    public PageResult<Emp> findpage(EmpQueryParam param) {
        IPage<Emp> ipage=new Page<>(param.getPage(),param.getPageSize());

        if (!CollectionUtils.isEmpty(ipage.getRecords())){
            LambdaQueryWrapper<Emp> queryMapper = new LambdaQueryWrapper<Emp>()
                    .like(param.getName() != null, Emp::getName, param.getName())
                    .eq(param.getGender() != null, Emp::getGender, param.getGender())
                    .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd())
                    .orderByDesc(Emp::getUpdateTime);
            IPage<Emp> page1 = this.page(ipage, queryMapper);
            List<Emp> records = page1.getRecords();
            List<Integer> list = records.stream().map(e -> e.getDeptId()).distinct().toList();
            List<Dept> depts = deptService.listByIds(list);
            for (Emp record : records) {
                depts.stream().filter(s -> s.getId().equals(record.getDeptId())).findFirst()
                        .ifPresent(dept -> record.setDeptName(dept.getName()));
            }
            return new PageResult<>(page1.getTotal(),page1.getRecords());
        }
        return null;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmp(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            this.save(emp);
            List<EmpExpr> exprList = emp.getExprList();
            exprList
            .forEach(e -> e.setEmpId(emp.getId()));
            empExprMapper.insert(emp.getExprList());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            empLogMapper.insert(new EmpLog(null,emp.getId(),LocalDateTime.now(),"INSERT",null,"json"));
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) {
        this.removeByIds(ids);
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId,ids));
    }

    @Override
    public Emp selectById(Integer id) {
        Emp emp = this.getById(id);
        List<EmpExpr> empExprs = empExprMapper.selectList(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, id));
        emp.setExprList(empExprs);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmpById(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId,emp.getId()));
        empExprMapper.insert(emp.getExprList());
    }
}
